 package com.atguigu.srb.core.listener;

 import com.alibaba.excel.context.AnalysisContext;
 import com.alibaba.excel.event.AnalysisEventListener;
 import com.atguigu.srb.core.mapper.DictMapper;
 import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
 import lombok.NoArgsConstructor;
 import lombok.extern.slf4j.Slf4j;

 import javax.annotation.Resource;
 import java.util.ArrayList;
 import java.util.List;

 @Slf4j
 @NoArgsConstructor
 public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
     @Resource
     private DictMapper dictMapper;
     private List<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
     //每五条数据存储一个
     private static final int BATCH_COUNT = 5;

     public ExcelDictDTOListener(DictMapper dictMapper) {
         this.dictMapper = dictMapper;
     }

     @Override
     public void invoke(ExcelDictDTO data, AnalysisContext context) {
         log.info("解析到一条记录: {}", data);
         excelDictDTOS.add(data);
         //调用mapper层的save方法
         if(excelDictDTOS.size()>=BATCH_COUNT){
             saveDate();
             excelDictDTOS.clear();
         }
     }

     @Override
     public void doAfterAllAnalysed(AnalysisContext context) {
         log.info("所有数据解析完成！");
     }

     private void saveDate(){
         log.info("开始插入字典");
         dictMapper.insertBatch(excelDictDTOS);
         log.info("插入字典完成");
     }
 }
